package com.stdz.counter.core.thread;

import com.stdz.counter.core.cache.MeterInfoCache;
import com.stdz.counter.dao.MeterInfoDao;
import com.stdz.counter.dao.ParamDao;
import com.stdz.counter.entity.MeterInfo;
import com.stdz.counter.entity.Param;
import com.stdz.counter.utils.ParamHelper;
import com.stdz.counter.utils.ResourceUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Resource;
import java.util.List;

/**
 *
 */
public class ConfigRefreshThread implements Runnable {

    private static transient Logger logger = LoggerFactory.getLogger(ConfigRefreshThread.class);

    @Resource
    private MeterInfoDao meterInfoDao;
    @Resource
    private ParamDao paramDao;

    public ConfigRefreshThread() {
        super();
        ResourceUtil.autowired(this);
    }

    public void run() {
        logger.info("config refresh thread run start");
        this.refreshConfigs();
        this.refreshComPorts();
        logger.info("config refresh thread run end");
    }

    public void refreshConfigs() {
        try {
            List<Param> params = paramDao.queryAllParams();
            ParamHelper.reloadParams(params);
        } catch (Throwable t) {
            logger.error("refresh params error:", t);
        }

    }

    public void refreshComPorts() {
        List<String> comPorts = meterInfoDao.queryAllComPorts();
        MeterInfoCache.getInstance().cacheComPorts(comPorts);
        if (comPorts != null && comPorts.size() > 0) {
            for (String comPort : comPorts) {
                try {
                    this.refreshComMeters(comPort);
                } catch (Throwable t) {
                    logger.error("refresh com meterInfos exception:", t);
                }
            }
        }
    }

    public void refreshComMeters(String comPort) {
        List<MeterInfo> meterInfos = meterInfoDao.queryMeterInfosByCom(comPort);
        MeterInfoCache.getInstance().cacheComMeterInfos(comPort, meterInfos);
    }
}
